package restless.aimovement.astar.analyzers {
	
	import flash.geom.Point;
	import restless.aimovement.astar.Analyzer;
	import restless.aimovement.astar.interfaces.IMap;
	import restless.aimovement.astar.interfaces.IPositionTile;
	import restless.aimovement.astar.interfaces.IWalkableTile;
	
	/**
	 * The SmartClippingAnalyzer allows the path to go diagonal, but only if the adjecent horizontal & vertical tiles are free.
	 * If the path would go 'right + up', both 'right' and 'up' should be walkable
	 * @author Jeroen
	 */
	
	public class SmartClippingAnalyzer extends Analyzer {
		
		public function SmartClippingAnalyzer() {
			
		}
		
		override protected function analyze(mainTile:*, allNeighbours:Array, neighboursLeft:Array, map:IMap):Array {
			var main:IPositionTile = mainTile as IPositionTile;
			var mainPos:Point = main.position;
			var newLeft:Array = [];
			
			var currentTile:IPositionTile;
			var currentPos:Point;
			var tile:IWalkableTile;
			var tile2:IWalkableTile;
			var p:Point;
			var i:Number = 0;
			
			for (i; i < neighboursLeft.length; i++) {
				currentTile = neighboursLeft[i] as IPositionTile;
				currentPos = currentTile.position;
				
				if (currentPos.x == mainPos.x || currentPos.y == mainPos.y) {
					newLeft.push(currentTile);
				} else {
					if(currentPos.x < mainPos.x) {
						if (currentPos.y < mainPos.y) {
							p = mainPos;
							p.x--;
							tile = IWalkableTile(map.getTileAt(p));
							
							p = mainPos;
							p.y--;
							tile2 = IWalkableTile(map.getTileAt(p));
							if (tile.walkable && tile2.walkable) { newLeft.push(currentTile); }
						} else {
							p = mainPos;
							p.x--;
							tile = IWalkableTile(map.getTileAt(p));
							
							p = mainPos;
							p.y++;
							tile2 = IWalkableTile(map.getTileAt(p);
							if(tile.walkable && tile2.walkable) { newLeft.push(currentTile); }
						}
					} else {
						if (currentPos.y < mainPos.y) {
							p = mainPos;
							p.x++;
							tile = IWalkableTile(map.getTileAt(p));
							
							p = mainPos;
							p.y--;
							tile2 = IWalkableTile(map.getTileAt(p));
							if(tile.walkable && tile2.walkable) { newLeft.push(currentTile); }
						} else {
							p = mainPos;
							p.x++;
							tile = IWalkableTile(map.getTileAt(p));
							
							p = mainPos;
							p.y++;
							tile2 = IWalkableTile(map.getTileAt(p));
							if(tile.walkable && tile2.walkable) { newLeft.push(currentTile); }
						}
					}
				}
			}
			
			return newLeft;
		}
	}
}
